<?php
/**
 * @author HungDV7
 *
 */
class CommentsController extends AppController {
	var $name = 'Comments';
	/**
	 * add comment to particular post
	 *
	 * @param string $postID        	
	 */
	
	public function beforeFilter() {
		parent::beforeFilter();
		// Allow users to register and logout.
		$this->Auth->allow('add');
	}
	
	public function add() {
		// if method is 'post', begin add comment
		if ($this->request->is ( 'post' )) {
			$this->Comment->create ();
			
			/*
			 * print_r($this->request->data); exit;
			 */
			
			// get data from request parameters
			$commentData = array (
					'fullname' => $this->request->data ['fullname'],
					'content' => $this->request->data ['content'],
					'post_id' => $this->request->data ['post_id'] 
			);
			
			// save new comment for particular post
			if ($this->Comment->save ( $commentData )) {
				$this->Session->setFlash ( 'Comments Save', 'default', array (
						'class' => 'alert alert-success' 
				) );
			} else {
				// error when comment cannot be save
				$this->Session->setFlash ( 'unable to save comment', 'default', array (
						'class' => 'alert alert-danger' 
				) );
			}
			
			// set redirect to view post detail
			return $this->redirect ( array (
					'controller' => 'posts',
					'action' => 'detail',
					$commentData ['post_id'] 
			) );
		} else {
			throw new MethodNotAllowedException ();
		}
	}
	
	/**
	 * delete the comment record, base on comment id, submit with 'POST' method
	 *
	 * @throws MethodNotAllowedException if request method type is 'GET'
	 */
	public function delete() {
		if ($this->request->is ( 'post' )) {
			// delete data in db, cascade setting help delete depedent child data
			$id = $this->request->data ['comment_id'];
			$postID = $this->request->data ['post_id'];
			
			// begin deleting
			if ($this->Comment->delete ( $id )) {
				$this->Session->setFlash ( 'Comment is deleted', 'default', array (
						'class' => 'alert alert-success' 
				) );
			} else {
				// error when comment cannot be delete
				$this->Session->setFlash ( 'Unable to delete comment', 'default', array (
						'class' => 'alert alert-danger' 
				) );
			}
			return $this->redirect ( array (
					'controller' => 'posts',
					'action' => 'detail',
					$postID 
			) );
		} else {
			throw new MethodNotAllowedException ();
		}
	}
}